package weaver.interfaces.ldjc.demoSAPToOA;

import com.engine.ld.utils.ResourceUtil;
import com.engine.ld.utils.WorkflowCreateHandler;
import com.weaver.general.BaseBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import weaver.conn.RecordSet;
import weaver.interfaces.schedule.BaseCronJob;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ZhangLei
 * @date 2021/7/19
 * SAP发起
 * 创建采购订单流程
 */
public class demoImpl extends BaseCronJob implements demo {
    private final static BaseBean bb = new BaseBean();
    private String workflowId = ResourceUtil.getKey("CgxxworkflowId");
    private List<Map<String, String>> dealResult = new ArrayList<>();//存储解析后的值
    private String id = "";//记录主表id
    private String requestId = "";
    //        主表字段：去掉了LOEKZ1、ZJTBS字段(前者因为字段重复，后者因为数据库中没有此字段)
    private final static String[] mainParams = {"LIFNR", "MATNR", "INFNR", "ESOKZ", "VERKF", "TELF1", "MEINS", "UMREN", "UMREZ",
            "URZLA", "ZFLAG", "LOEKZ", "EKORG", "APLFZ", "EKGRP", "NORBM", "MINBM", "UEBTO", "MWSKZ", "WEBRE",
            "NETPR", "WAERS", "PEINH", "BPRME", "KSCHL", "PRDAT", "BPUMN", "BPUMZ", "ZYXQBS", "DATAB", "DATBI",
            "KSTBM", "KONMS", "KBETR", "ZTJYW", "ZCZTJ"};
    //        明细表字段
    private final static String[] dtParams = {"LIFNR", "MATNR", "INFNR", "ZJTBS", "DATAB", "DATBI", "KSTBM", "KONMS", "KBETR"};

    @Override
    public String createCgddWorkflow(String xml) {
//        解析SAP传递的XML
        try {
            dealResult = dealXml(xml);
        } catch (Exception e) {
            e.printStackTrace();
            bb.writeLog("xml解析失败");
        }
//        将解析结果存入数据库
        //      将主表信息存储到数据库
        Map<String, String> mainMap = dealResult.get(0);
        String mainSql = insertSql("formtable_main_155", mainMap);
        RecordSet rsMain = new RecordSet();
        boolean query = rsMain.executeQuery(mainSql);
//        获取主表ID
        String selectIdSql = selectId("formtable_main_155", mainMap);
        RecordSet rsGetId = new RecordSet();
        rsGetId.executeQuery(selectIdSql);
        if (rsGetId.next()){
            id = rsGetId.getString("id");
        }else {
            bb.writeLog("id获取失败");
        }
        if (query) {
            bb.writeLog("数据插入成功");
//            创建流程
            execute();
        } else {
            bb.writeLog("数据插入失败");
        }

        return requestId;
    }

    @Override
    public void execute() {
        String requestName = "采购信息流程";
        bb.writeLog("采购信息流程开始创建");

//        获取当前时间
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        String NY = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(c.getTime());

        WorkflowCreateHandler handler = new WorkflowCreateHandler();
        String requestid = handler.WorkflowCreateByRequestMap(id, workflowId, requestName, "0", dealResult.get(0));
        requestId = requestid;
        bb.writeLog("采购信息流程的requestid为："+requestid);
    }

    /**
     * 解析xml的方法
     * 入参：xml的字符串
     * 出参：含解析xml结果的List集合
     */
    private static List<Map<String, String>> dealXml(String xml) throws DocumentException {
        String realXml = getRealXml(xml);
        List<Map<String, String>> dealResult = new ArrayList<>();
        SAXReader reader = new SAXReader();
        Document document = null;
        document = reader.read(new ByteArrayInputStream(realXml.getBytes(StandardCharsets.UTF_8)));

        Element root = document.getRootElement();


//        按照元素的标签名获得对应的节点集合
        Map<String, String> headResult = new HashMap<>();
        Map<String, String> itemResult = new HashMap<>();

        List<Element> head1 = root.elements("HEAD");
        for (Element elementHead : head1) {
            for (String mainParam : mainParams) {
                headResult.put(mainParam.toLowerCase(), elementHead.elementTextTrim(mainParam));
            }
        }
        List<Element> item = root.elements("ITEM");
        for (Element elementItem : item) {
            for (String dtParam : dtParams) {
                itemResult.put(dtParam.toLowerCase(), elementItem.elementTextTrim(dtParam));
            }
        }
        dealResult.add(headResult);
        dealResult.add(itemResult);

        return dealResult;
    }

    /*
     * 获取正确的xml
     * */
    private static String getRealXml(String xml) {
        if (!xml.contains("<_--5CTYPE_--3DSTRING>")) {
            return xml;
        }
        int start = xml.indexOf("<_--5CTYPE_--3DSTRING>") + "<_--5CTYPE_--3DSTRING>".length();
        int end = xml.indexOf("</_--5CTYPE_--3DSTRING>");
        return xml.substring(start, end).trim();
    }

    /*
     * 主表插入sql方法
     * */
    private static String insertSql(String tableName, Map<String, String> mainMap) {
        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(tableName).append("(");
        for (int i = 0; i < mainParams.length; i++) {
            if (i != mainParams.length - 1) {
                sql.append(mainParams[i]).append(",");
            } else {
                sql.append(mainParams[i]).append(") ");
            }
        }
        sql.append("VALUES (");
        for (int i = 0; i < mainParams.length; i++) {
            if (i != mainParams.length - 1) {
//                sql.append(mainMap.get(mainParams[i].toLowerCase())).append(",");
                if ("".equals(mainMap.get(mainParams[i].toLowerCase()))) {
                    sql.append("NULL").append(",");
                } else {
                    sql.append(mainMap.get(mainParams[i].toLowerCase())).append(",");
                }
            } else {
                if ("".equals(mainMap.get(mainParams[i].toLowerCase()))) {
                    sql.append("NULL").append(")");
                } else {
                    sql.append(mainMap.get(mainParams[i].toLowerCase())).append(")");
                }
            }
        }
        return sql.toString();
    }

    /*
     * 获取插入数据的id
     * */
    private static String selectId(String tableName, Map<String, String> mainMap) {
        String selectSql = "SELECT id from " + tableName + " where ";
        for (int i = 0; i < mainParams.length; i++) {
            if (i != mainParams.length - 1) {
                if (!"".equals(mainMap.get(mainParams[i].toLowerCase()))) {
                    selectSql += mainParams[i].toLowerCase() + " = '" + mainMap.get(mainParams[i].toLowerCase()) + "' and ";
                }
            } else {
                if (!"".equals(mainMap.get(mainParams[i].toLowerCase()))) {
                    selectSql += mainParams[i].toLowerCase() + " = '" + mainMap.get(mainParams[i].toLowerCase()) + "'";
                }
            }
        }
        return selectSql;
    }
}
